//
//  firendCircledb.m
//  tcpoctest
//
//  Created by gump on 4/15/13.
//  Copyright (c) 2013 gump. All rights reserved.
//

#import "firendCircledb.h"
#import "FirendCircleDataSource.h"

#import "sendPotocol.h"

@implementation firendCircledb

-(void)creatTable
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    [db executeUpdate:@"create table if not exists firendcircle(selfmail text,\
newsid text)"];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)initData
{
    if (IsHaveFirendCircle()) {
        if (db == nil) {
            return;
        }
        
        pthread_mutex_lock(&mutexdatabase);
        
        [db open];
        
        NSString *strsql = [NSString stringWithFormat:@"SELECT * FROM firendcircle where selfmail = '%@'"
                            ,[DataControl shareControl].personDS.uinfo.mail];
        FMResultSet *s = [db executeQuery:strsql];
        
        [[DataControl shareControl].fircirDS RemovAllArr];
        
        while ([s next])
        {
            [[DataControl shareControl].fircirDS AddFirCirArrFirst:[s stringForColumn:@"newsid"]];
        }
        
        [db close];
        
        pthread_mutex_unlock(&mutexdatabase);
    }
    else
    {
        [[netManager sharedNetManager].sendp SendMainIndex:ID_MI_FIRENDCIRCLE
                                           WithSecondIndex:FC_NEW];
    }
}

-(void)insertFC:(NSString *)fs
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString *strsql = [NSString stringWithFormat:@"SELECT * FROM firendcircle \
where selfmail = '%@' and newsid = '%@'"
                        ,[DataControl shareControl].personDS.uinfo.mail
                        ,fs];
    
    FMResultSet *s = [db executeQuery:strsql];
    
    if (![s next]) {
        strsql = [NSString stringWithFormat:@"insert into firendcircle \
(selfmail,newsid) \
values('%@','%@')"
                  ,[DataControl shareControl].personDS.uinfo.mail
                  ,fs];
        
        [db executeUpdate:strsql];
    }
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)DelNewsByID:(NSString *)newsid
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString *strsql = [NSString stringWithFormat:@"DELETE FROM firendcircle WHERE newsid = '%@'"
                        ,newsid];
    [db executeUpdate:strsql];
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

@end
